<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card v-loading="loading">
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <page-tools :show-before="true">
              <span slot="before">共{{ page.total }}条记录</span>
              <template slot="after">
                <el-button
                  :disabled="!checkPermission('api-role-post')"
                  icon="el-icon-plus"
                  size="small"
                  type="primary"
                  @click="showDialog = true"
                >
                  新增角色
                </el-button>
              </template>
            </page-tools>
            <!-- 表格 -->
            <el-table border :data="list" stripe highlight-current-row>
              <el-table-column align="center" type="index" label="序号" width="100" />
              <!-- <el-table-column align="center" prop="roleid" label="id" width="120" /> -->
              <el-table-column align="center" prop="name" label="名称" />
              <el-table-column align="center" prop="details" label="描述" />
              <el-table-column align="center" label="操作">
                <template slot-scope="{ row }">
                  <el-button :disabled="!checkPermission('api-roleright-put')" size="small" type="success" @click="showEditRoleRight(row.roleid)">分配权限</el-button>
                  <el-button :disabled="!checkPermission('api-role-put')" size="small" type="primary" @click="editRole(row.roleid)">编辑</el-button>
                  <el-button :disabled="!checkPermission('api-role-delete')" size="small" type="danger" @click="deleteRole(row.roleid)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <!-- 放置分页组件 -->
            <el-row type="flex" justify="end" align="middle" style="height:60px">
              <el-pagination
                layout="total, sizes, prev, pager, next, jumper"
                :total="page.total"
                :current-page="page.page"
                :page-size="page.pagesize"
                :page-sizes="[1, 5, 10, 20]"
                @current-change="changePage"
                @size-change="handleSizeChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>

        <!--编辑添加角色框-->
        <el-dialog title="编辑角色" :visible="showDialog" @close="btnCancel">
          <el-form ref="roleFormRef" :model="roleForm" :rules="rules" label-width="120px">
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="roleForm.name" />
            </el-form-item>
            <el-form-item label="角色描述">
              <el-input v-model="roleForm.details" />
            </el-form-item>
          </el-form>
          <!-- 底部 -->
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button size="small" @click="btnCancel">取消</el-button>
              <el-button size="small" type="primary" @click="btnOK">确定</el-button>
            </el-col>
          </el-row>
        </el-dialog>

        <!--弹出分配角色权限框-->
        <el-dialog
          v-loading="loading"
          title="请选择给改角色的权限"
          :visible.sync="dialogVisible"
          custom-class="dialogClass"
          width="30%"
          top="5vh"
          @closed="cleardata()"
        >
          <el-tree
            ref="tree"
            get-checked-nodes
            :data="rightlist"
            show-checkbox
            check-on-click-node
            node-key="id"
            accordion
            default-expand-all
            highlight-current
            :default-checked-keys="checkKey"
            :props="defaultProps"
          />
          <span slot="footer" class="dialog-footer">
            <el-button @click="cleardata">取 消</el-button>
            <el-button type="primary" @click="updateRoleRight">确 定</el-button>
          </span>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getAllRole, deleteRole, editRole, addRole, getRoleDetail, getRoleRightDetail, editRoleRight } from '@/api/role'
import { getPermissionList } from '@/api/permission'

export default {
  data() {
    return {
      loading: true,
      list: [], // 承接数组
      page: {
        // 放置页码及相关数据
        page: 1,
        pagesize: 5,
        total: 0 // 记录总数
      },
      showDialog: false,
      // 专门接收新增或者编辑的编辑的表单数据
      roleForm: {},
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      },
      dialogVisible: false,
      rightlist: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 选中的复选框id
      checkKey: [],
      role: {
        right_id: '',
        role_ids: ''
      }
    }
  },
  created() {
    this.getRoleList() // 获取角色列表
  },
  methods: {
    async getRoleList() {
      this.loading = true
      const { rows, total } = await getAllRole(this.page.page, this.page.pagesize)
      this.list = rows
      this.page.total = total
      this.loading = false
    },
    changePage(newPage) {
      // newPage是当前点击的页码
      this.page.page = newPage // 将当前页码赋值给当前的最新页码
      this.getRoleList()
    },
    handleSizeChange(newSize) {
      this.page.pagesize = newSize // 将当前页码赋值给当前的最新页码
      this.getRoleList()
    },
    async deleteRole(id) {
      //  提示
      try {
        await this.$confirm('确认删除该角色吗')
        // 只有点击了确定 才能进入到下方
        await deleteRole(id) // 调用删除接口
        this.getRoleList() // 重新加载数据
        this.$message.success('删除角色成功')
      } catch (error) {
        // console.log(error)
      }
    },
    async editRole(id) {
      this.roleForm = await getRoleDetail(id)
      this.showDialog = true // 为了不出现闪烁的问题 先获取数据 再弹出层
    },
    async btnOK() {
      try {
        await this.$refs.roleFormRef.validate()
        // 只有校验通过的情况下 才会执行await的下方内容
        // roleForm这个对象有id就是编辑 没有id就是新增

        if (this.roleForm.roleid || this.roleForm.roleid === 0) {
          this.roleForm.roleid = this.roleForm.roleid.toString()
          await editRole(this.roleForm)
        } else {
          // 新增业务
          await addRole(this.roleForm)
        }
        // 重新拉取数据
        this.getRoleList()
        this.$message.success('操作成功')
        this.showDialog = false
      } catch (error) {
        // console.log(error)
      }
    },
    btnCancel() {
      this.roleForm = {
        name: '',
        details: ''
      }
      // 移除校验
      this.$refs.roleFormRef.resetFields()
      this.showDialog = false
    },
    async showEditRoleRight(id) {
      this.dialogVisible = true
      this.rightlist = await getPermissionList()
      console.log(this.rightlist)
      this.getRoleRight(id)
      this.role.role_ids = id.toString()
    },
    async getRoleRight(id) {
      this.checkKey = await getRoleRightDetail(id)
    },
    async updateRoleRight() {
      try {
        await this.$confirm('确认更改角色权限吗') // 只有点击了确定 才能进入到下方
        var arr = []
        this.$refs.tree.getCheckedNodes().forEach(val => {
          arr.push(val.id)
        })
        const set = new Set(arr) // 去掉重复数据，返回结果是'set'
        this.role.right_id = [...set].join('-')
        await editRoleRight(this.role)
        this.getRoleList() // 重新加载数据
        this.cleardata()
        this.$message.success('更新成功')
      } catch (error) {
        // console.log(error)
      }
    },
    cleardata() {
      this.dialogVisible = false
      this.rightlist = []
      // 选中的复选框id
      this.checkKey = []
      this.role = {
        right_id: '',
        role_ids: ''
      }
    }
  }
}
</script>

<style lang="less" scoped>
.dialogClass{
  height: 500px;
}
</style>
